import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart';
import 'package:wowhy/models/error_info.dart';
import 'package:wowhy/service_locator.dart';
import 'package:wowhy/services/navigate_service.dart';

import '../../../utils/message.dart';
import '../../../services/auth_service.dart';

import 'action.dart';
import 'state.dart';

Effect<LoginFormState> buildEffect() {
  return combineEffects(<Object, Effect<LoginFormState>>{
    LoginFormAction.onLogin: _onLogin,
  });
}

void _onLogin(dynamic action, Context<LoginFormState> ctx) async {
  LoginFormState state = action.payload ?? ctx.state;
  try {
    await ctx.dispatch(LoginFormActionCreator.submitting(true));
    String username = state.usernameController.text;
    String password = state.passwordController.text;
    bool result = await MessageUtil.blocking(ctx.context, () {
      return AuthService.instance.login(username, password);
    });

    if (result == true) {
      getIt<NavigateService>().pop(true);
    }
  } on ErrorInfo {
    // nothing
  } finally {
    await ctx.dispatch(LoginFormActionCreator.submitting(false));
  }
}
